﻿using System;
using System.IO;
using System.Net;

namespace Comdiv.QWeb.Remoting {
	public class RemoteConnection : ConnectionBase {
		private readonly string url;

		public RemoteConnection(string url) {
			this.url = url;
		}

		protected override QWebResult internalCall(QWebQuery query) {
			var u = url;
			if (!u.EndsWith("/")) {
				u += "/";
			}
			var req = query.CreateWebRequest(u);
			if (null != credentials) {
				req.Credentials = credentials;
			}
			else {
				req.UseDefaultCredentials = true;
			}
			var result = new QWebResult();


			try {
				var resp = (HttpWebResponse) req.GetResponse();
				result.LastModified = resp.LastModified;
				var header = resp.Headers["ETag"];
				if (header != null) {
					result.ETag = header;
				}
				result.Status = (int) resp.StatusCode;
				try {
					using (var r = resp.GetResponseStream()) {
						result.Content = new StreamReader(r).ReadToEnd();
					}
				}
				catch (Exception ex) {
					result.Error = ex;
				}
			}
			catch (WebException ex) {
				var errorResponse = (HttpWebResponse) ex.Response;
				result.Status = (int) errorResponse.StatusCode;
				try {
					using (var resst = errorResponse.GetResponseStream()) {
						var sr = new StreamReader(resst);
						result.ErrorString = sr.ReadToEnd();
					}
				}
				catch (Exception ex2) {
					result.Error = ex2;
				}
			}
			catch (Exception ex) {
				result.Error = ex;
			}
			return result;
		}
	}
}